﻿using RemoteData.core;
using RemoteData.model.setting;
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;


namespace RemoteData.view.setting
{
    /// <summary>
    /// GlobalSettingDlg.xaml 的交互逻辑
    /// </summary>
    public partial class GlobalSettingDlg : Window
    {
        private GlobalSettingDlgViewModel windowViewModel;
        public GlobalSettingDlg()
        {
            InitializeComponent();

            windowViewModel = new GlobalSettingDlgViewModel();
            this.DataContext = windowViewModel;

            this.btnOK.Click += new RoutedEventHandler(OK_Click);
            this.btnCancel.Click += new RoutedEventHandler(Cancel_Click);
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }
            GlobalSettingSave();

            this.DialogResult = true;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private bool CheckInput()
        {
            BindingExpression beListenerPort = tbListenerPort.GetBindingExpression(TextBox.TextProperty);
            beListenerPort.UpdateSource();

            bool hasError = (Validation.GetHasError(tbListenerPort));

            return !hasError;
        }

        private void GlobalSettingSave()
        {
            GlobalSetting globalSetting = TW_App.globalSetting;
            globalSetting.listenerPort = windowViewModel.globalSetting.listenerPort;

            globalSetting.Save();
        }
    }

    public class GlobalSettingDlgViewModel : ViewModelBase
    {
        public GlobalSettingDlgViewModel()
        {
            globalSetting = new GlobalSettingViewModel(TW_App.globalSetting);
        }

        private GlobalSettingViewModel m_globalSetting;
        public GlobalSettingViewModel globalSetting
        {
            get { return m_globalSetting; }
            set
            {
                m_globalSetting = value;
                NotifyPropertyChanged();
            }
        }
    }
}
